// pages/statistics/statistics.js
const app = getApp()

Page({
  data: {
    currentYear: new Date().getFullYear(),
    currentMonth: new Date().getMonth() + 1,
    calendarData: [],
    overview: null,
    trendData: null,
    categoryStats: null,
    isLoading: false
  },

  onLoad() {
    this.loadOverview()
    this.loadCalendar()
    this.loadTrend()
    this.loadCategoryStats()
  },

  // 加载概览数据
  loadOverview() {
    this.setData({ isLoading: true })
    app.request('/statistics/overview', 'GET')
      .then(res => {
        this.setData({
          overview: res.data
        })
      })
      .catch(err => {
        console.error('加载概览数据失败:', err)
      })
      .finally(() => {
        this.setData({ isLoading: false })
      })
  },

  // 加载日历数据
  loadCalendar() {
    app.request('/statistics/calendar', 'GET', {
      year: this.data.currentYear,
      month: this.data.currentMonth
    })
      .then(res => {
        this.setData({
          calendarData: res.data.days
        })
      })
      .catch(err => {
        console.error('加载日历数据失败:', err)
      })
  },

  // 加载趋势数据
  loadTrend() {
    app.request('/statistics/trend', 'GET')
      .then(res => {
        this.setData({
          trendData: res.data
        })
      })
      .catch(err => {
        console.error('加载趋势数据失败:', err)
      })
  },

  // 加载分类统计
  loadCategoryStats() {
    app.request('/statistics/category', 'GET')
      .then(res => {
        this.setData({
          categoryStats: res.data
        })
      })
      .catch(err => {
        console.error('加载分类统计失败:', err)
      })
  },

  // 上一月
  prevMonth() {
    let month = this.data.currentMonth - 1
    let year = this.data.currentYear
    
    if (month < 1) {
      month = 12
      year--
    }
    
    this.setData({
      currentYear: year,
      currentMonth: month
    }, () => {
      this.loadCalendar()
    })
  },

  // 下一月
  nextMonth() {
    let month = this.data.currentMonth + 1
    let year = this.data.currentYear
    
    if (month > 12) {
      month = 1
      year++
    }
    
    this.setData({
      currentYear: year,
      currentMonth: month
    }, () => {
      this.loadCalendar()
    })
  },

  // 生成日历
  generateCalendar() {
    const year = this.data.currentYear
    const month = this.data.currentMonth
    const firstDay = new Date(year, month - 1, 1)
    const lastDay = new Date(year, month, 0)
    const startDate = new Date(firstDay)
    startDate.setDate(startDate.getDate() - firstDay.getDay())
    
    const calendar = []
    const currentDay = new Date(startDate)
    
    for (let i = 0; i < 42; i++) {
      const dateStr = this.formatDate(currentDay)
      const isCurrentMonth = currentDay.getMonth() === month - 1
      const dayData = this.data.calendarData.find(d => d.date === dateStr)
      
      calendar.push({
        date: dateStr,
        day: currentDay.getDate(),
        isCurrentMonth: isCurrentMonth,
        hasCheckIn: dayData ? dayData.has_check_in : false,
        itemCount: dayData ? dayData.item_count : 0
      })
      
      currentDay.setDate(currentDay.getDate() + 1)
    }
    
    return calendar
  },

  // 格式化日期
  formatDate(date) {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
  },

  // 点击日历日期
  onDayClick(e) {
    const date = e.currentTarget.dataset.date
    const hasCheckIn = e.currentTarget.dataset.hasCheckIn
    
    if (hasCheckIn) {
      wx.showModal({
        title: date,
        content: '查看当日打卡详情',
        success: (res) => {
          if (res.confirm) {
            // 跳转到详情页面
            console.log('查看详情:', date)
          }
        }
      })
    }
  },

  // 刷新数据
  refreshData() {
    this.loadOverview()
    this.loadCalendar()
    this.loadTrend()
    this.loadCategoryStats()
  }
})